<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use App\Models\User;
use App\Models\UserIncome;
use DB;

class UserBill extends Model
{
    //用户支出记录表
    const CREATED_AT = 'insert_time';
    /**
     * 与模型关联的数据表。
     *
     * @var string
     */
    protected $table = 'lexiang_bill_log';

    protected $primaryKey = 'bill_id';

    public $timestamps = false;

    /**
     * 可以被批量赋值的属性。
     *
     * @var array
     */
    protected $fillable = ['users_id','payee_id','price','bewrite','effect','insert_time'];

    /**
     * 添加消费记录
     */
    public function insertBill($info,$userid)
    {
    	$nowtime = time();
    	$createData = [
    		'users_id'=>$userid,
    		'payee_id'=>$info['payee_id'],
    		'price'=>$info['price'],
    		'bewrite'=>$info['bewrite'],
    		'effect'=>$info['effect'],
    		'insert_time'=>$nowtime,
    	];
    	// 事务处理
    	DB::beginTransaction();
    	try {
    		$insertRes = self::create($createData);
	        if(!$insertRes){
	        	DB::rollBack();
	        	return ['success'=>false,'message'=>'系统出错，请稍后重试！','code'=>'1'];
	        }
	        $account_m = self::refreshAccount($userid);
	    	$user = User::find($userid);
	    	if($user->account<$info['price']){
                // 回滚
	    		DB::rollBack();
	    		return ['success'=>false,'message'=>'该用户的余额不足以完成本次扣款！','code'=>'2'];
	    	}
	    	$user->account = $user->account-$info['price'];
	    	$editRes = $user->save();
	    	if(!$editRes){
	    		DB::rollBack();
	    		return ['success'=>false,'message'=>'系统出错，请稍后重试！','code'=>'4'];
	    	}
	    	if($insertRes && $editRes){
                // 提交
	    		DB::commit();
	    		return ['success'=>true,'message'=>'扣款成功！','code'=>'0'];
	    	}
    	} catch (\Exception $e) {
    		DB::rollBack();
    		return ['success'=>false,'message'=>'系统出错，请稍后重试！','code'=>'3'];
    	}
    }

    /**
     * 刷新用户账户余额
     */
    public static function refreshAccount($userid)
    {
    	$incomes = UserIncome::where('users_id',$userid)->select('income_value')->get()->toArray();
    	$bills = self::where('users_id',$userid)->select()->get()->toArray();
    	$incomes = array_column($incomes, 'income_value');
    	$bills = array_column($bills, 'price');
    	$puls_sum = array_sum($incomes);
    	$reduce_sum = array_sum($bills);
    	$final = $puls_sum - $reduce_sum;
    	if($final<0){
    		$final = 0;
    	}
    	$user = new User;
    	$user->account = $final;
    	$result = $user->save();
    	if($result){
    		return $final;
    	}else{
    		return false;
    	}
    }
}
